//
//  YMTestUserViewController.m
//  YMMedical
//
//  Created by y s on 2023/7/26.
//

#import "YMTestUserViewController.h"
#import "YMTestUserListCell.h"
#import "YMHomeTipInforAlert.h"
#import "YMAddOrEditTestUserVC.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "YMMainDefaultEmptyCell.h"

#import "YMMineService.h"

@interface YMTestUserViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tvMain;

@property (nonatomic, strong) NSMutableArray *arrList;

@property (nonatomic, assign) NSInteger pageNo;


@end

@implementation YMTestUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadData:YES];
}

- (void)setUI{
    self.fd_interactivePopDisabled = YES;
    [self showNavTitle:KLanguage(@"tester_man_txt")];
    WEAK_SELF;
    [SNavUtil rightIcon:self icon:@"mine_nav_add_new_user" onClick:^{
        [weakSelf addNewOrEditTestUserVC:YES dictInfor:nil];
    }];
    
    [self.view addSubview:self.tvMain];
    [self.tvMain mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.mas_equalTo(0);
    }];
    
    [SThemeUtil refershHead:self.tvMain block:^{
        [weakSelf loadData:YES];
    }];
    [SThemeUtil refershFooter:self.tvMain block:^{
        [weakSelf loadData:NO];
    }];
}

- (void)loadData:(BOOL)isRefresh{
    if (isRefresh){
        _pageNo = 1;
    }
    WEAK_SELF;
    [YMMineService requestMineTesteeListDataWithPage:_pageNo needpage:1 success:^(NSArray * _Nonnull arrData) {
        [weakSelf.tvMain.mj_header endRefreshing];
        if (isRefresh){
            [weakSelf.arrList removeAllObjects];
            [weakSelf.tvMain.mj_footer endRefreshing];
        }else{
            if (arrData.count > 0){
                [weakSelf.tvMain.mj_footer endRefreshing];
            }else{
                [weakSelf.tvMain.mj_footer endRefreshingWithNoMoreData];
            }
        }
        if (arrData.count > 0){
            [weakSelf.arrList addObjectsFromArray:arrData];
            weakSelf.pageNo++;
        }
        [weakSelf.tvMain reloadData];
    } failure:^(NSString * _Nonnull message) {
        [weakSelf.tvMain.mj_header endRefreshing];
        [weakSelf.tvMain.mj_footer endRefreshing];
        [SHUD showInfo:message];
    }];
}

- (void)deleteClickAction:(NSIndexPath *)indexPath{
    //删除操作
    NSDictionary *dict = [SDataUtil dictOf:self.arrList[indexPath.section]];
    NSString *userId = [SDataUtil stringOf:dict[@"id"] valid:@""];
   
    WEAK_SELF;
    [YMMineService requestMineDeleteTesteeWithRowId:userId success:^{
        [weakSelf.arrList removeObjectAtIndex:indexPath.section];  //删除数组里的数据
        [weakSelf.tvMain deleteRow:0 inSection:indexPath.section withRowAnimation:UITableViewRowAnimationLeft];
        [weakSelf.tvMain reloadData];
    } failure:^(NSString * _Nonnull message) {
        [SHUD showInfo:message];
    }];
}
- (void)addNewOrEditTestUserVC:(BOOL)isAddNew
                     dictInfor:(NSDictionary *)dict{
    YMAddOrEditTestUserVC *vc = [[YMAddOrEditTestUserVC alloc] init];
    vc.dictInfor = dict;
    vc.isAddNew = isAddNew;
    [SJumpUtil pushVC:vc animated:YES];
}

#pragma mark -- UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.arrList.count > 0){
        return self.arrList.count;
    }else{
        return 1;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.arrList.count > 0){
        YMTestUserListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YMTestUserListCell" forIndexPath:indexPath];
        if (indexPath.section < self.arrList.count){
            cell.dict = [SDataUtil dictOf:self.arrList[indexPath.section]];
        }
        return cell;
    }else{
        YMMainDefaultEmptyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YMMainDefaultEmptyCell" forIndexPath:indexPath];
        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@，%@",KLanguage(@"status_empty"),KLanguage(@"no_device_2_txt")]];
        [attr addAttributes:@{NSForegroundColorAttributeName: STheme.D12} range:NSMakeRange(KLanguage(@"status_empty").length+1, KLanguage(@"no_device_2_txt").length)];
        cell.attrDes = attr;
        WEAK_SELF;
        cell.desClickBlock = ^{
            [weakSelf addNewOrEditTestUserVC:YES dictInfor:nil];
        };
        return cell;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return [[UIView alloc] init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.arrList.count > 0){
        return [YMTestUserListCell getCellHeight];
    }else{
        return [YMMainDefaultEmptyCell getCellHeight];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0){
        return [SFitUtil fit:15];
    }
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return [SFitUtil fit:15];
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAK_SELF;
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:KLanguage(@"remove_txt") handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        YMHomeTipInforAlert *alert = [[YMHomeTipInforAlert alloc] init];
        alert.iconName = @"alert_tips_infor_delete_icon";
        alert.strContent = KLanguage(@"remove_tester_all_dele_txt");
        alert.sureBlock = ^{
            if (indexPath.section < weakSelf.arrList.count){
                [weakSelf deleteClickAction:indexPath];
            }
        };
        [alert show];
    }];
    deleteAction.backgroundColor = [SUIUtil colorOf:0xFF3141];
    UITableViewRowAction *editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:KLanguage(@"edit_txt") handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
       //编辑
        if (indexPath.section < weakSelf.arrList.count){
            NSDictionary *dict = [SDataUtil dictOf:weakSelf.arrList[indexPath.section]];
            [weakSelf addNewOrEditTestUserVC:NO dictInfor:dict];
        }
    }];
    editAction.backgroundColor = [SUIUtil colorOf:0x1677FF];
    return @[deleteAction,editAction];
}

/**自定义设置iOS11系统下的左滑删除按钮大小*/
//开始编辑左滑删除
- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    if (@available(iOS 13.0, *)) {
        for (UIView *subView in self.tvMain.subviews) {
            if([subView isKindOfClass:NSClassFromString(@"_UITableViewCellSwipeContainerView")]) {
                [self changeEditCellButtonUI:subView];
            }
        }
    }else if (@available(iOS 11.0, *)) {
        for (UIView *subView in self.tvMain.subviews) {
            [self changeEditCellButtonUI:subView];
        }
    }
}
//判断是否显示左滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.arrList.count > 0){
        return YES;
    }
    return NO;
}

- (void)changeEditCellButtonUI:(UIView *)subView{
    for (UIView *subViewss in subView.subviews) {
        if([subViewss isKindOfClass:NSClassFromString(@"UISwipeActionPullView")]) {
            subViewss.backgroundColor = STheme.D9;
            for (UIView *subview3 in subViewss.subviews) {
                if([subview3 isKindOfClass:NSClassFromString(@"UISwipeActionStandardButton")]) {
                    UIButton *btn = (UIButton *)subview3;
                    [btn setTitleColor:STheme.D9 forState:UIControlStateNormal];
                    btn.titleLabel.font = [SFitUtil fitBoldFont:15];
                }
            }
        }
    }
}

#pragma mark -- setter and getter
- (UITableView *)tvMain{
    if (!_tvMain) {
        _tvMain = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tvMain.backgroundColor = [UIColor clearColor];
        _tvMain.delegate   = self;
        _tvMain.dataSource = self;
        _tvMain.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tvMain.showsVerticalScrollIndicator   = NO;
        _tvMain.showsHorizontalScrollIndicator = NO;
        _tvMain.estimatedRowHeight = 0;
        _tvMain.estimatedSectionHeaderHeight = 0;
        _tvMain.estimatedSectionFooterHeight = 0;
        _tvMain.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        [_tvMain registerClass:[YMTestUserListCell class] forCellReuseIdentifier:@"YMTestUserListCell"];
        [_tvMain registerClass:[YMMainDefaultEmptyCell class] forCellReuseIdentifier:@"YMMainDefaultEmptyCell"];
        
    }
    return _tvMain;
}
- (NSMutableArray *)arrList{
    if (_arrList == nil){
        _arrList = [[NSMutableArray alloc] init];
    }
    return _arrList;
}

@end
